package lion.dev.image.format;

import java.awt.image.BufferedImage;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.jhlabs.image.ImageUtils;

import lion.dev.image.FileFormatWriter;

public class FileFormatBMP extends FileFormatWriter {

	public FileFormatBMP() {
		super("BMP", "image/bmp", ".bmp");
	}

	@Override
	public void writeImage(OutputStream out, BufferedImage image) throws IOException {

		int w = image.getWidth();
		int h = image.getHeight();
		DataOutputStream dos = new DataOutputStream(out);
		int offset = 54;
		int imageSize = 4 * w * h;
		int size = offset + imageSize;
		dos.writeByte(66);
		dos.writeByte(77);
		writeLEInt(dos, size);
		writeLEInt(dos, 0);
		writeLEInt(dos, offset);
		writeLEInt(dos, 40);
		writeLEInt(dos, w);
		writeLEInt(dos, h);
		dos.writeByte(1);
		dos.writeByte(0);
		dos.writeByte(32);
		dos.writeByte(0);
		writeLEInt(dos, 0);
		writeLEInt(dos, imageSize);
		writeLEInt(dos, 2835);
		writeLEInt(dos, 2835);
		writeLEInt(dos, 0);
		writeLEInt(dos, 0);

		int[] pixels = null;
		for (int y = 0; y < h; y++) {
			pixels = ImageUtils.getRGB(image, 0, h - y - 1, w, 1, pixels);
			for (int x = 0; x < w; x++) {
				writeLEInt(dos, pixels[x]);
			}
		}
		dos.close();
	}

	private void writeLEInt(DataOutputStream dos, int n) throws IOException {

		dos.writeByte(n);
		dos.writeByte(n >> 8);
		dos.writeByte(n >> 16);
		dos.writeByte(n >> 24);
	}
}
